UIOptionalGift = Class("UIOptionalGift", UIComponentBase)

function UIOptionalGift:OnCreate(id, parent)
    self.activeId = id
    self.parent = parent
    self.drawWrapper = GoWrapper.New()
    self.lihui = self:GetChild("lihui");
    self.lihui2 = self:GetChild("lihui2");
    self.banner = self:GetChild("banner")
    self.bannerChar = self:GetChild("bannerChar")
    self.title = self:GetChild("title")
    self.titleTips = self:GetChild("bannerText")
    self.giftList = self:GetChild("giftList")
    self.ctrlItem = CtrlManager.GetCtrl(PanelNames.Item);
    self.bannerTips = {};
    for i = 1, 8 do
        table.insert(self.bannerTips, self:GetChild("bannerTips"..i));
    end
    self.giftList.scrollPane.onScroll:Add(self.OnListScroll, self);
    self.isFirst = true;
end

function UIOptionalGift:OnListScroll()
    if self.endItems ~= nil then
        local isBottomMost = self.giftList.scrollPane.isBottomMost;
        if self.itemNum == 3 or isBottomMost then
            self.parent:updateListPoint(false);
            self.pointValue = false;
        else
            local flag = false;
            for k, v in pairs(self.endItems) do
                if self.giftList:IsChildInView(v) then
                    flag = true;
                    break;
                end
            end
            if flag then
                if self.pointValue == nil or self.pointValue then
                    self.pointValue = false;
                    self.parent:updateListPoint(false);
                end
            else
                if self.pointValue == nil or not self.pointValue then
                    self.pointValue = true;
                    self.parent:updateListPoint(true);
                end
            end
        end
    end
end

function UIOptionalGift:Refresh()
    self.startItem = nil;
    self.endItems = nil;
    self.endItems = {};
    self.pointValue = nil;
    logicMgr.CostManager.updateActiveOpenStatus(self.activeId);
    self.severData, self.itemTableData, self.modelTableData = logicMgr.CostManager.getCostData(self.activeId);
    logicMgr.CostManager.updateCostHelp(self, self:GetChild("help"), self.modelTableData);
    self.optionItemTableData = G.dataTable["t_optionitem"];
    self.countDownNum = self.severData.endTime - HelperFunc.GetServerTime();
    self:RemoveTimeCall(self.OnCountDown);
    if self.countDownNum <= 0 then
        self.titleTips.text = getLanguage("Sys_ActivityEnd");
    else
        self:TimeCall(self.OnCountDown, 1000, -1);
        self.titleTips.text = string.format(getLanguage(self.modelTableData.f_BannerTips, nil, "%s"),HelperFunc.GetSurpTimeStr(self.countDownNum));
    end
    for k, v in pairs(decodeJsonStrToTabel(self.modelTableData.f_BannerTipsShow)) do
        if self.bannerTips[k] ~= nil then
            if v ~= "" then
                self.bannerTips[k].url = tostring(v);
            else
                self.bannerTips[k].url = "";
            end
        else
            break;
        end
    end
    self.bannerChar.url = tostring(self.modelTableData.f_BannerHead);
    self.banner.url = tostring(self.modelTableData.f_Banner);
    self.title.text = getLanguage(self.modelTableData.f_Title);
    self.chooseItemList = {};
    self.itemObjList = {};
    self.itemNum = #self.severData.items;
    self.giftList:RemoveChildrenToPool();
    for k, v in pairs(self.severData.items) do
        local tableData = self.itemTableData[tostring(v.subId)];
        self:initChooseItem(v.chooseItemIdList, tableData);
        local item = self.giftList:AddItemFromPool()
        self:updateItem(item, v, tableData);
        self.itemObjList[tostring(tableData.f_ItemId)] = item;
        --end
    end
    local localItem = self.giftList:AddItemFromPool()
    --table.insert(self.endItems, localItem);
    local bgmask = localItem:GetController("bgmask");
    bgmask.selectedIndex = 1;

    if self.isFirst then
        self.isFirst = false;
        self.giftList:ScrollToView(0, false);
    end
    self:OnListScroll();

    self.parent:updateCostShowByTableOrJson(self.modelTableData.f_ResourceShow);
    logicMgr.CostManager.updateLiHui(self, self.drawWrapper, self.lihui, self.lihui2, self.modelTableData.f_HeroSpine)
end

function UIOptionalGift:updateItem(itemObj, serverData, tableData)
   -- local mark = itemObj:GetChild("mark");
    local title = itemObj:GetChild("title");
    local time = itemObj:GetChild("time");
    local buy = itemObj:GetChild("buy");
    local choose = itemObj:GetChild("choose");
    local buyNum = itemObj:GetChild("buyNum");
    local fristItem = itemObj:GetChild("fristItem");
    local stateController = itemObj:GetController("state");
    local bgmask = itemObj:GetController("bgmask");
    bgmask.selectedIndex = 0;
    if serverData.residue > 0 then
        stateController.selectedIndex = 0;
    else
        stateController.selectedIndex = 1;
        table.insert(self.endItems, itemObj);
    end
    --mark.url = tostring(tableData.f_ConnerMark);
    title.text = getLanguage(tableData.f_Title, nil, "");
    buyNum.text = getLanguage("SellLimit")..serverData.residue.."/"..tableData.f_Count;
    if tableData.f_Price == 0 then
        buy.title = getLanguage("FreeMoney");
    else
        buy.title = "￥"..tableData.f_Price;
    end
    buy.onClick:Clear();
    buy.onClick:Add(function() self:ClickBuy(serverData.subId, tableData.f_ProductId, 1, tableData.f_Price); end);
    choose.onClick:Clear();
    choose.onClick:Add(function() self:showChooseTips(serverData.subId) end);
    logicMgr.CostManager.RefreshItem(fristItem, decodeJsonStrToTabel(tableData.f_DefaultItem)[1]);
    self:updateChooseItem(itemObj, tableData.f_ItemId);
end

function UIOptionalGift:showChooseTips(id, itemIndex)
    showUI(PanelNames.UIOptionalGiftTips, function (data)
        self.chooseItemList[tostring(id)] = data;
        self:updateChooseItem(self.itemObjList[tostring(id)], id);
    end, self.activeId, id, nil, itemIndex, clone(self.chooseItemList[tostring(id)]));
end

function UIOptionalGift:updateChooseItem(itemObj, id)
    if itemObj == nil then
        return ;
    end
    local itemList = itemObj:GetChild("itemList");
    local showMoney = itemObj:GetController("showMoney");
    itemList:RemoveChildrenToPool();
    local flag = 0;
    for i = 1, #self.chooseItemList[tostring(id)] do
        local item = itemList:AddItemFromPool();
        flag = flag + self:UpdataItem(item, id , i);
    end
    if flag > 0 then
        showMoney.selectedIndex = 0;
    else
        showMoney.selectedIndex = 1;
    end
    if #self.chooseItemList[tostring(id)] <= 4 then
        itemList.scrollPane.touchEffect = false;
    else
        itemList.scrollPane.touchEffect = true;
    end
end

function UIOptionalGift:UpdataItem(itemObj, optionId, itemIndex)
    if itemObj == nil then
        return 0;
    end
    local choose = itemObj:GetController("choose");
    local item = itemObj:GetChild("item");
    local itemData = self.chooseItemList[tostring(optionId)][itemIndex];
    itemObj.onClick:Clear();
    itemObj.onClick:Add(function() self:showChooseTips(optionId, itemIndex) end);
    if itemData == nil or #itemData == 0 then
        choose.selectedIndex = 0;
        return 1;
    else
        choose.selectedIndex = 1;
        logicMgr.CostManager.RefreshItem(item, itemData);
        item.onClick:Clear();
    end
    return 0;
end

function UIOptionalGift:initChooseItem(serverData, tableData)
    local items = {};
    for i = 1, tableData.f_OptionCount do
        local data = self:findItemById(self:findChooseItemsByIdAndIndex(tableData.f_ItemId, i), serverData[i]);
        table.insert(items, data);
    end
    self.chooseItemList[tostring(tableData.f_ItemId)] = items;
end

function UIOptionalGift:findChooseItemsByIdAndIndex(id, index)
    for k, v in pairs(self.optionItemTableData) do
        if v.f_BelongActiveId == tonumber(id) and v.f_OptionOrder == index then
            return decodeJsonStrToTabel(v.f_OptionItem);
        end
    end
    return {};
end

function UIOptionalGift:findItemById(items, id)
    for k, v in pairs(items) do
        if v[1] == id then
            return v;
        end
    end
    return {};
end

function UIOptionalGift:OnCountDown()
    self.countDownNum = self.countDownNum - 1;
    if self.countDownNum <= 0 then
        self.titleTips.text = getLanguage("Sys_ActivityEnd");
        return true;
    end
    self.titleTips.text = string.format(getLanguage(self.modelTableData.f_BannerTips, nil, "%s"),HelperFunc.GetSurpTimeStr(self.countDownNum));
end

function UIOptionalGift:ClickBuy(id, payId, num, money)
    logicMgr.CostManager.getRewardByIdAndIndex(self.activeId, id, payId, num, money, self.onBuySuccess, self);
end

function UIOptionalGift:onBuySuccess()
    --UISysTips.AddMsg("购买成功");
end

-- 卸载
function UIOptionalGift:OnDestroy()
    if self.RoleLihui then
        destroyImmediate(self.RoleLihui)
        self.RoleLihui = nil
    end
    if self._package and UIPackage.GetById(self._package) then
        UIPackage.RemovePackage(self._package)
    end
    self.giftList.scrollPane.onScroll:Remove(self.OnListScroll)
    self.endItems = nil;
end